//
//  UPCustomAlertView.m
//  Uang Pasti
//
//  Created by 李永彬 on 2025/8/18.
//

#import "UPCustomAlertView.h"
#import <objc/runtime.h>
#import "UPAlertPrivacyView.h"

@interface UPCustomAlertView()<UPAlertPrivacyViewDelegate>

// UI Components
@property (nonatomic, strong) UIView *backgroundView;
@property (nonatomic, strong) UIImageView *backgroundImageView;
@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic, strong) UILabel *contentLabel;
@property (nonatomic, strong) UIStackView *buttonStackView;
@property (nonatomic, strong) UIView *customContentView; // 新增：自定义内容视图
@property (nonatomic, strong) UIButton *closeButton;

// Configuration
@property (nonatomic, assign) UPAlertViewStyle style;
@property (nonatomic, weak) UIView *superView;
@property (nonatomic, assign) BOOL hasCustomView; // 新增：标记是否使用自定义视图
@property (nonatomic, strong) UPAlertPrivacyView *privacyView;
@property (nonatomic, assign) BOOL isAlertVisiable;
@property (nonatomic, assign) BOOL isPrivacySelected;

@end

@implementation UPCustomAlertView

#pragma mark - Initialization

- (instancetype)initWithBackgroundImage:(UIImage *)backgroundImage style:(UPAlertViewStyle)style {
    self = [super init];
    if (self) {
        _style = style;
        _hasCustomView = NO;
        _isButtonClickDismiss = YES;
        
        [self setupBaseStyle];
        [self setupBackgroundView];
        [self setupBackgroundImage:backgroundImage];
        [self setupTitleLabel];
        [self setupContentLabel];
        [self setupButtonStack];
        [self setupCloseButton];
        [self setupConstraintsWithImage:backgroundImage];
        [self setupPrivacyView];
    }
    return self;
}

- (instancetype)initWithCustomView:(UIView *)customView style:(UPAlertViewStyle)style {
    self = [super init];
    if (self) {
        _style = style;
        _hasCustomView = YES;
        _customContentView = customView;
        _isButtonClickDismiss = YES;
        
        [self setupBaseStyle];
        [self setupBackgroundView];
        [self setupCustomContentView:customView];
        [self setupCloseButton];
        [self setupConstraintsWithCustomView:customView];
    }
    return self;
}

- (void)setupBaseStyle {
    self.layer.cornerRadius = 12.0;
    self.clipsToBounds = YES;
    self.backgroundColor = [UIColor clearColor];
}

- (void)setupBackgroundView {
    _backgroundView = [UIView new];
    _backgroundView.backgroundColor = [UIColor colorWithWhite:0 alpha:0.5];
    _backgroundView.alpha = 0;
}

- (void)setupBackgroundImage:(UIImage *)image {
    _backgroundImageView = [UIImageView new];
    _backgroundImageView.image = image;
    _backgroundImageView.contentMode = UIViewContentModeScaleAspectFit;
    [self addSubview:_backgroundImageView];
}

- (void)setupCustomContentView:(UIView *)customView {
    [self addSubview:customView];
    _customContentView = customView;
}

- (void)setupTitleLabel {
    _titleLabel = [UILabel new];
    _titleLabel.textAlignment = NSTextAlignmentCenter;
    _titleLabel.numberOfLines = 0;
    [self addSubview:_titleLabel];
}

- (BOOL)isPrivacySelected {
    return self.privacyView.isSelected;
}

- (void)setShowPrivacy:(BOOL)showPrivacy
{
    _showPrivacy = showPrivacy;
    _privacyView.hidden = !showPrivacy;

    [_privacyView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.contentLabel.mas_bottom).offset(15);
        make.leading.trailing.equalTo(self).inset(20);
        make.height.mas_equalTo(30);
    }];
    
//    // Content Label
//    [_contentLabel mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.top.equalTo(self.titleLabel.mas_bottom).offset(15);
//        make.leading.trailing.equalTo(self).inset(20);
//    }];
    
    // Button Stack
    [_buttonStackView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.privacyView.mas_bottom).offset(20);
        make.centerX.equalTo(self).inset(20);
        make.bottom.equalTo(self.backgroundImageView).offset(-10);
    }];
}

- (void)setupPrivacyView  {
    _privacyView = [[UPAlertPrivacyView alloc] initWithPolicyText:LocalizableForKey(@"alertPrivacyText") highlightText:LocalizableForKey(@"alertPrivacyText")];
    _privacyView.delegate = self;
    _privacyView.hidden = YES;
    [self addSubview:_privacyView];
}

- (void)setupContentLabel {
    _contentLabel = [UILabel new];
    _contentLabel.textAlignment = NSTextAlignmentCenter;
    _contentLabel.numberOfLines = 0;
    _contentLabel.textColor = [UIColor colorWithHexString:@"000000"];
    [self addSubview:_contentLabel];
}

- (void)setupButtonStack {
    _buttonStackView = [UIStackView new];
    _buttonStackView.axis = UILayoutConstraintAxisVertical;
    _buttonStackView.spacing = 5.0;
    _buttonStackView.distribution = UIStackViewDistributionFill;
    _buttonStackView.alignment = UIStackViewAlignmentFill;
    
    [self addSubview:_buttonStackView];
}

- (void)setupCloseButton {
    _closeButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [_closeButton setImage:[UIImage imageNamed:@"alert_close"] forState:UIControlStateNormal];
    [_closeButton addTarget:self action:@selector(closeAlertView) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:_closeButton];
}

#pragma mark - Layout

- (void)setupConstraintsWithImage:(UIImage *)image {
    CGFloat screenWidth = [UIScreen mainScreen].bounds.size.width;
    
    // Background Image
    CGFloat width = screenWidth - 40;
    
    CGFloat aspectRatio = 1.0;
    if (image.size.height > 0 && image.size.width) {
        aspectRatio = image.size.height / image.size.width;
    }
    CGFloat height = width * aspectRatio;
    [_backgroundImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        if (self.style == UPAlertViewStyleBottomSheet) {
            make.top.equalTo(self.closeButton.mas_bottom).offset(10);
            make.bottom.equalTo(self);
        } else {
            make.bottom.equalTo(self.closeButton.mas_top).offset(-10);
            make.top.equalTo(self);
        }
        make.centerX.equalTo(self);
        make.width.mas_equalTo(width);
        make.height.mas_equalTo(height);
    }];
    
    if (self.style == UPAlertViewStyleBottomSheet) {
        [_closeButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self).offset(10);
            make.width.mas_equalTo(25);
            make.height.mas_equalTo(25);
            make.trailing.equalTo(self);
        }];
    } else {
        [_closeButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.bottom.equalTo(self.mas_bottom).offset(-10);
            make.width.mas_equalTo(25);
            make.height.mas_equalTo(25);
            make.centerX.equalTo(self);
        }];
    }
    
    // Title Label
    [_titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.backgroundImageView).offset(20);
        make.leading.trailing.equalTo(self).inset(40);
        make.height.equalTo(@40);
    }];
    
    // Content Label
    [_contentLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.titleLabel.mas_bottom).offset(15);
        make.leading.trailing.equalTo(self).inset(20);
    }];
    
    // Button Stack
    [_buttonStackView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.contentLabel.mas_bottom).offset(20);
        make.centerX.equalTo(self).inset(20);
        make.bottom.equalTo(self.backgroundImageView).offset(-10);
    }];
    
    [self mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.equalTo(@(screenWidth - 40));
    }];
}

- (void)setupConstraintsWithCustomView:(UIView *)customView {
    CGFloat screenWidth = [UIScreen mainScreen].bounds.size.width;
    
    // Custom View
    [customView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.bottom.equalTo(self);
        make.top.equalTo(self.closeButton.mas_bottom).offset(10);
    }];
    
    if (self.style == UPAlertViewStyleBottomSheet) {
        [_closeButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self);
            make.width.mas_equalTo(25);
            make.height.mas_equalTo(25);
            make.trailing.equalTo(self);
        }];
    } else {
        [_closeButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.bottom.equalTo(self.mas_bottom).offset(-10);
            make.width.mas_equalTo(25);
            make.height.mas_equalTo(25);
            make.centerX.equalTo(self);
        }];
    }

    [self mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.equalTo(@(customView.bounds.size.width ?: screenWidth - 40));
        make.height.equalTo(@(customView.bounds.size.height ?: customView.intrinsicContentSize.height));
    }];
}

#pragma mark - Public Methods

- (void)setTitle:(NSString *)title font:(UIFont *)font {
    if (_hasCustomView) {
        NSLog(@"Warning: Cannot set title when using custom view");
        return;
    }
    
    _titleLabel.text = title;
    NSMutableDictionary *attributes = [NSMutableDictionary dictionary];
    
    if (font) {
        attributes[NSFontAttributeName] = font;
        _titleLabel.font = font;
    }
    
    attributes[NSForegroundColorAttributeName] = [UIColor colorWithHexString:@"FFFFFF"];
    attributes[NSStrokeColorAttributeName] = [UIColor colorWithHexString:@"000000"];
    attributes[NSStrokeWidthAttributeName] = @(-4);
    
    _titleLabel.attributedText = [[NSAttributedString alloc] initWithString:title ?: @"" attributes:attributes];
}

- (void)setContent:(NSString *)content font:(UIFont *)font {
    if (_hasCustomView) {
        NSLog(@"Warning: Cannot set content when using custom view");
        return;
    }
    
    _contentLabel.text = content;
    if (font) _contentLabel.font = font;
    _contentLabel.textColor = [UIColor colorWithHexString:@"000000"];
}

- (void)addButtonWithTitle:(NSString *)title style:(UPButtonStyle)style handler:(void (^)(void))handler {
    if (_hasCustomView) {
        NSLog(@"Warning: Cannot add button when using custom view");
        return;
    }
    
    UIColor *normalColor, *textColor;
    UIFont *font = [UIFont systemFontOfSize:13 weight:UIFontWeightSemibold];
    UIImage *image = nil;
    switch (style) {
        case UPButtonStyleDefault:
            normalColor = [UIColor systemBlueColor];
            image = [UIImage imageNamed:@"button_bg_style1"];
            textColor = [UIColor colorWithHexString:@"#000000"];
            break;
            
        case UPButtonStyleDestructive:
            normalColor = [UIColor clearColor];
            textColor = [UIColor colorWithHexString:@"#858585"];
            break;
            
        case UPButtonStyleCancel:
            normalColor = [UIColor clearColor];
            textColor = [UIColor colorWithHexString:@"#858585"];
            break;
            
        case UPButtonStyleCustom:
        default:
            normalColor = [UIColor clearColor];
            textColor = [UIColor blackColor];
            break;
    }
    
    [self addButtonWithTitle:title
       normalBackgroundColor:normalColor
                       image:image
                  titleColor:textColor
                        font:font
                     handler:handler];
}

- (void)addButtonWithTitle:(NSString *)title
     normalBackgroundColor:(UIColor *)normalColor
                     image:(UIImage *)image
                titleColor:(UIColor *)titleColor
                      font:(UIFont *)font
                   handler:(void (^)(void))handler {
    
    if (_hasCustomView) {
        NSLog(@"Warning: Cannot add button when using custom view");
        return;
    }
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.layer.cornerRadius = 6.0;
    button.clipsToBounds = YES;
    
    // Configure Button
    [button setTitle:title forState:UIControlStateNormal];
    [button setTitleColor:titleColor forState:UIControlStateNormal];
    if (font) button.titleLabel.font = font;
    
    // Background Images
    if (image) {
        button.contentMode = UIViewContentModeCenter;
        button.imageView.contentMode = UIViewContentModeScaleAspectFit;
        
        UIImage *resizableImage = [image resizableImageWithCapInsets:UIEdgeInsetsZero
                                                        resizingMode:UIImageResizingModeStretch];
        [button setBackgroundImage:resizableImage forState:UIControlStateNormal];
    } else {
        [button setBackgroundImage:[self imageWithColor:normalColor] forState:UIControlStateNormal];
    }

    // Add Handler
    if (handler) {
        objc_setAssociatedObject(button, "buttonHandler", handler, OBJC_ASSOCIATION_COPY_NONATOMIC);
        [button addTarget:self action:@selector(buttonTapped:) forControlEvents:UIControlEventTouchUpInside];
    }
    
    // Add to Stack
    [_buttonStackView addArrangedSubview:button];
    CGFloat height = 65.0;
    [button mas_makeConstraints:^(MASConstraintMaker *make) {
        if (image) {
            CGFloat aspectRatio = image.size.width / image.size.height;
            make.height.mas_equalTo(height);
            make.width.mas_equalTo(height * aspectRatio);
        } else {
            make.width.mas_equalTo(200);
            make.height.mas_equalTo(40);
        }
    }];
}

- (void)closeAlertView {
    [self dismiss];
}

#pragma mark - Show/Hide

- (void)showInView:(UIView *)superView {
    _superView = superView;
    
    // Add Background
    [superView addSubview:_backgroundView];
    [_backgroundView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(superView);
    }];
    
    // Add Alert
    [superView addSubview:self];
    
    // Add Tap Gesture
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismiss)];
//    [_backgroundView addGestureRecognizer:tap];
    
    // Layout Based on Style
    switch (_style) {
        case UPAlertViewStyleCenter: {
            [self mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerY.equalTo(superView).offset(-30);
                make.centerX.equalTo(superView);
            }];
        }
            break;
            
        case UPAlertViewStyleBottomSheet: {
            [self mas_makeConstraints:^(MASConstraintMaker *make) {
                make.leading.trailing.equalTo(superView).inset(20);
                make.bottom.equalTo(superView).offset(self.bounds.size.height);
            }];
            [superView layoutIfNeeded];
            
            [self mas_updateConstraints:^(MASConstraintMaker *make) {
                make.bottom.equalTo(superView);
            }];
        }
            break;
    }
    self.isAlertVisiable = YES;
    self.alpha = 0;
    self.superView.transform = CGAffineTransformMakeScale(0.8, 0.8);
    [UIView animateWithDuration:0.3 delay:0 usingSpringWithDamping:0.7 initialSpringVelocity:0.5 options: UIViewAnimationOptionCurveEaseInOut animations:^{
        self.backgroundView.alpha = 1;
        self.alpha = 1;
        self.superview.transform = CGAffineTransformIdentity;
    } completion:^(BOOL finished) {
        
    }];
}

- (void)dismiss {
    self.isAlertVisiable = NO;
    [UIView animateWithDuration:0.3 animations:^{
        self.backgroundView.alpha = 0;
        self.alpha = 0;
        
        if (self.style == UPAlertViewStyleBottomSheet) {
            [self mas_updateConstraints:^(MASConstraintMaker *make) {
                make.bottom.equalTo(self.superView).offset(self.bounds.size.height);
            }];
            [self.superView layoutIfNeeded];
        }
    } completion:^(BOOL finished) {
        [self.backgroundView removeFromSuperview];
        [self removeFromSuperview];
    }];
}

#pragma mark - Button Action

- (void)buttonTapped:(UIButton *)sender {
    void (^handler)(void) = objc_getAssociatedObject(sender, "buttonHandler");
    if (handler) handler();
    if (self.isButtonClickDismiss) {
        [self dismiss];
    }
}

#pragma mark - Helper

- (UIImage *)imageWithColor:(UIColor *)color {
    CGRect rect = CGRectMake(0, 0, 1, 1);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, color.CGColor);
    CGContextFillRect(context, rect);
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

#pragma mark - UPAlertPrivacyViewDelegate
- (void)privacyPolicyView:(UPAlertPrivacyView *)view didTapHighlightText:(NSString *)text {
    if (self.privacyTapBlock) {
        self.privacyTapBlock();
    }
}

@end
